package org.lql.algo.codecrush.hot100.array;

/**
 * @author: liangqinglong
 * @date: 2025-08-30 21:38
 * @description: 41. 缺失的第一个正数 <a href="https://leetcode.cn/problems/first-missing-positive/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class FirstMissingPositive {


	public int firstMissingPositive(int[] nums) {
		int n = nums.length;
		// 将 nums[i] 放到正确的位置上
		for (int i = 0; i < n; i++) {
			while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) {
				int temp = nums[nums[i] - 1];
				nums[nums[i] - 1] = nums[i];
				nums[i] = temp;
			}
		}
		for (int i = 0; i < n; i++) {
			if (nums[i] != i + 1) {
				return i + 1;
			}
		}
		return n + 1;
	}

	public static void main(String[] args) {
		FirstMissingPositive solution = new FirstMissingPositive();
		// 2
		System.out.println(solution.firstMissingPositive(new int[]{3, 4, -1, 1}));
		// 3
		System.out.println(solution.firstMissingPositive(new int[]{1, 2, 0}));
		// 1
		System.out.println(solution.firstMissingPositive(new int[]{7, 8, 9, 11, 12}));
	}
}
